//
//  NetworkFailurePlugin.swift
//  LiveTrivia
//
//  Created by Gesen on 2017/11/22.
//  Copyright © 2017年 LiveTrivia. All rights reserved.
//
//  处理需要打点的错误情况

import Moya
//import Result

final class NetworkAnalyticsPlugin: PluginType {
    
    func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        
        let baseUrl = target.baseURL.absoluteString
        let path = target.path
        
        if case .success = result {
            
            DispatchQueue.global().async {
                if
                    let data = result.value?.data,
                    let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments),
                    !JSONSerialization.isValidJSONObject(json) {
                    let info = "url: \(baseUrl)| path: \(path) | error: 数据格式错误，无法解析)"
//                    Analytics.event(.http_request_success, info: info)
                }
            }
        }
        
        if case .failure = result {
            
            var code = result.error?.response?.statusCode ?? 0
            if case .underlying(let error, _)? = result.error {
                if (error as NSError).code == NSURLErrorCancelled {
                    return
                }
                // 过滤NSError类型错误
                if error._domain == NSURLErrorDomain {
                    code = (error as NSError).code
                }
            }
            // 请求失败统计
            let info = "url: \(baseUrl)| path: \(path) | error: \((result.error?.localizedDescription ?? "请求失败"))"
//            Analytics.event(.http_request_failure, info: info)
            // http错误状态码统计
            print(code)
        }
    }
}
